package jnpf.service.impl;

import jnpf.util.UserProvider;
import jnpf.entity.*;
import jnpf.mapper.ThemeStructureVersionMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.themestructureversion.*;
import cn.hutool.core.util.ObjectUtil;
import jnpf.util.GeneraterSwapUtil;

import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import jnpf.model.QueryModel;
import java.util.stream.Collectors;
import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.util.*;
import java.util.*;
import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;
/**
 *
 * themeStructureVersion
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-09
 */
@Service
public class ThemeStructureVersionServiceImpl extends ServiceImpl<ThemeStructureVersionMapper, ThemeStructureVersionEntity> implements ThemeStructureVersionService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Override
    public List<ThemeStructureVersionEntity> getList(ThemeStructureVersionPagination themeStructureVersionPagination){
        return getTypeList(themeStructureVersionPagination,themeStructureVersionPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<ThemeStructureVersionEntity> getTypeList(ThemeStructureVersionPagination themeStructureVersionPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
        List<List<String>> intersectionList =new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? ThemeStructureVersionConstant.getAppColumnData() : ThemeStructureVersionConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total=0;
        int themeStructureVersionNum =0;
        QueryWrapper<ThemeStructureVersionEntity> themeStructureVersionQueryWrapper=new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp ="";
        if (ObjectUtil.isNotEmpty(themeStructureVersionPagination.getSuperQueryJson())){
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList  = new ArrayList<>();
            String queryJson = themeStructureVersionPagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<ThemeStructureVersionEntity> themeStructureVersionSuperWrapper = new QueryWrapper<>();
            themeStructureVersionSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(themeStructureVersionSuperWrapper,ThemeStructureVersionEntity.class,queryJson,"0"));
            int themeStructureVersionNum1 = themeStructureVersionSuperWrapper.getExpression().getNormal().size();
            if (themeStructureVersionNum1>0){
                List<String> themeStructureVersionList =this.list(themeStructureVersionSuperWrapper).stream().map(ThemeStructureVersionEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(themeStructureVersionList);
                intersectionSuperList.add(themeStructureVersionList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if(superOp.equalsIgnoreCase("and")){
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            }else{
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp ="";
        if (ObjectUtil.isNotEmpty(ruleJson)){
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList  = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<ThemeStructureVersionEntity> themeStructureVersionSuperWrapper = new QueryWrapper<>();
            themeStructureVersionSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(themeStructureVersionSuperWrapper,ThemeStructureVersionEntity.class,ruleJson,"0"));
            int themeStructureVersionNum1 = themeStructureVersionSuperWrapper.getExpression().getNormal().size();
            if (themeStructureVersionNum1>0){
                List<String> themeStructureVersionList =this.list(themeStructureVersionSuperWrapper).stream().map(ThemeStructureVersionEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(themeStructureVersionList);
                intersectionRuleList.add(themeStructureVersionList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if(ruleOp.equalsIgnoreCase("and")){
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            }else{
                allRuleIDlist = allRuleList;
            }
        }
    boolean pcPermission = false;
    boolean appPermission = false;
    if(isPc && pcPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object themeStructureVersionObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeStructureVersionQueryWrapper,ThemeStructureVersionEntity.class,themeStructureVersionPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(themeStructureVersionObj)){
        return new ArrayList<>();
        } else {
        themeStructureVersionQueryWrapper = (QueryWrapper<ThemeStructureVersionEntity>)themeStructureVersionObj;
        if( themeStructureVersionQueryWrapper.getExpression().getNormal().size()>0){
        themeStructureVersionNum++;
        }
        }
    }
    }
    if(!isPc && appPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object themeStructureVersionObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeStructureVersionQueryWrapper,ThemeStructureVersionEntity.class,themeStructureVersionPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(themeStructureVersionObj)){
        return new ArrayList<>();
        } else {
        themeStructureVersionQueryWrapper = (QueryWrapper<ThemeStructureVersionEntity>)themeStructureVersionObj;
        if( themeStructureVersionQueryWrapper.getExpression().getNormal().size()>0){
        themeStructureVersionNum++;
        }
        }


    }
    }
        if(isPc){
            if(ObjectUtil.isNotEmpty(themeStructureVersionPagination.getVersion())){
            themeStructureVersionNum++;

                String value = themeStructureVersionPagination.getVersion() instanceof List ?
                    JsonUtil.getObjectToString(themeStructureVersionPagination.getVersion()) :
                    String.valueOf(themeStructureVersionPagination.getVersion());
                themeStructureVersionQueryWrapper.lambda().like(ThemeStructureVersionEntity::getVersion,value);

            }

            if(ObjectUtil.isNotEmpty(themeStructureVersionPagination.getCreateuserid())){
            themeStructureVersionNum++;

        themeStructureVersionQueryWrapper.lambda().eq(ThemeStructureVersionEntity::getCreateuserid,themeStructureVersionPagination.getCreateuserid());

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total>0){
            if (intersection.size()==0){
                intersection.add("jnpfNullList");
            }
            themeStructureVersionQueryWrapper.lambda().in(ThemeStructureVersionEntity::getId, intersection);
        }
    //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)){
            if (allSuperIDlist.size()==0){
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            themeStructureVersionQueryWrapper.lambda().and(t->t.in(ThemeStructureVersionEntity::getId, finalAllSuperIDlist));
        }
    //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)){
            if (allRuleIDlist.size()==0){
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            themeStructureVersionQueryWrapper.lambda().and(t->t.in(ThemeStructureVersionEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if(StringUtil.isEmpty(themeStructureVersionPagination.getSidx())){
            themeStructureVersionQueryWrapper.lambda().orderByDesc(ThemeStructureVersionEntity::getId);
        }else{
            try {
                String sidx = themeStructureVersionPagination.getSidx();
                String[] strs= sidx.split("_name");
                ThemeStructureVersionEntity themeStructureVersionEntity = new ThemeStructureVersionEntity();
                Field declaredField = themeStructureVersionEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                themeStructureVersionQueryWrapper="asc".equals(themeStructureVersionPagination.getSort().toLowerCase())?themeStructureVersionQueryWrapper.orderByAsc(value):themeStructureVersionQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<ThemeStructureVersionEntity> page=new Page<>(themeStructureVersionPagination.getCurrentPage(), themeStructureVersionPagination.getPageSize());
                IPage<ThemeStructureVersionEntity> userIPage=this.page(page, themeStructureVersionQueryWrapper);
                return themeStructureVersionPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<ThemeStructureVersionEntity> list = new ArrayList();
                return themeStructureVersionPagination.setData(list, list.size());
            }
        }else{
            return this.list(themeStructureVersionQueryWrapper);
        }
    }
    @Override
    public ThemeStructureVersionEntity getInfo(String id){
        QueryWrapper<ThemeStructureVersionEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ThemeStructureVersionEntity::getId,id);
        return this.getOne(queryWrapper);
    }
    @Override
    public void create(ThemeStructureVersionEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String id, ThemeStructureVersionEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ThemeStructureVersionEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(ThemeStructureVersionForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id="";
        String countRecover = "";
        if (isUp){
            id = form.getId();
        }
        //主表字段验证
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param themeStructureVersionForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(ThemeStructureVersionForm themeStructureVersionForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        themeStructureVersionForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(ThemeStructureVersionConstant.getFormData(),themeStructureVersionForm),ThemeStructureVersionForm.class);
        ThemeStructureVersionEntity entity = JsonUtil.getJsonToBean(themeStructureVersionForm, ThemeStructureVersionEntity.class);

        if(isSave){
            String mainId =  RandomUtil.uuId() ;
        entity.setCreateuserid(userInfo.getUserId());
        entity.setCreatetime(DateUtil.getNowDate());
            entity.setId(mainId);
        }else{
        entity.setCreateuserid(userInfo.getUserId());
        entity.setCreatetime(DateUtil.getNowDate());
        }
        this.saveOrUpdate(entity);

    }
}
